package com.zho.common.social;

import static com.zho.util.Constants.Social.FACEBOOK_ACCESSTOKEN_URL;
import com.zho.common.utility.Constants;
import com.zho.domain.model.SnsPostingInfo;
import com.zho.util.Constants.Social;
import com.zho.util.Helpers;
import com.zho.util.Logit;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Parameter;
import com.restfb.types.FacebookType;
import com.restfb.types.Page;
import com.restfb.types.User;

/**
 * @ClassName: com.zho.common.social.FacebookPlugin
 * @Version 1.0
 * @author chu.anh.tuan
 * @CrDate February 09, 2012
 * 
 */
public class FacebookPlugin {

	private static Logit log = Logit.getInstance(FacebookPlugin.class);

	protected final static Integer SOCIAL_NETWORK_TYPE = 1;
	public static String APP_ID = "";
	public static String APP_SECRET = "";
	private static String CALLBACK_URL = "";
	private static String AUTHORIZATION_URL = "";
	public static String ACCESSTOKEN_URL = "";

	static {
		try {
			APP_ID = Helpers.getCgsProperty(Social.FACEBOOK_APP_ID).trim();
			APP_SECRET = Helpers.getCgsProperty(Social.FACEBOOK_APP_SECRET)
					.trim();
			AUTHORIZATION_URL = Helpers.getCgsProperty(
					Social.FACEBOOK_AUTHORIZATION_URL).trim();
			ACCESSTOKEN_URL = Helpers.getCgsProperty(FACEBOOK_ACCESSTOKEN_URL)
					.trim();
			CALLBACK_URL = Helpers.getCgsProperty(Social.CALLBACK_URL).trim()
					+ "?social=" + Social.FACEBOOK;
		} catch (Exception e) {
			log.error("FacebookPlugin load config fail", e);
		}
	}

	public static String getAuthorizationURL() {
		try {
			if (AUTHORIZATION_URL.indexOf("APP_ID") > 0
					&& AUTHORIZATION_URL.indexOf("REDIRECT_URL") > 0) {
				String url = AUTHORIZATION_URL;
				url = url.replaceAll("APP_ID", APP_ID);
				url = url.replaceAll("REDIRECT_URL", CALLBACK_URL);
				return url;
			} else
				return "";
		} catch (Exception e) {
			log.error("FacebookPlugin.getAuthorizationURL(): error", e);
			return null;
		}
	}

	public static String getAccessToken(String code) {
		if (Helpers.isEmpty(code)) {
			return null;
		}
		try {
			String access_token = "";

			HttpClient httpclient = new HttpClient();

			String url = ACCESSTOKEN_URL;
			url = url.replaceAll("APP_ID", APP_ID);
			url = url.replaceAll("APP_SECRET_KEY", APP_SECRET);
			url = url.replaceAll("REDIRECT_URL", CALLBACK_URL);
			url = url.replaceAll("AUTH_CODE", code);
			GetMethod method = new GetMethod(url);

			httpclient.executeMethod(method);

			String result = method.getResponseBodyAsString();

			String[] pairs = result.split("&");
			for (String pair : pairs) {
				String[] kv = pair.split("=");
				if (kv.length >= 1) {
					if (kv[0].equals("access_token")) {
						access_token = kv[1];
						break;
					}
				}
			}
			return access_token;
		} catch (Exception e) {
			log.error("FacebookPlugin.getAccessToken(String): error", e);
			return null;
		}
	}

	public static String getAccountName(String accessToken) {
		if (Helpers.isEmpty(accessToken)) {
			return null;
		}
		try {
			FacebookClient facebookClient = new DefaultFacebookClient(
					accessToken);
			User user = facebookClient.fetchObject("me", User.class);
			return user.getEmail();
		} catch (Exception e) {
			log.error("FacebookPlugin.getAccountName(String): error", e);
			return null;
		}
	}

	public static int postMessage(String accessToken, String message) {
		try {
			FacebookClient facebookClient = new DefaultFacebookClient(
					accessToken);
			FacebookType response = facebookClient
					.publish(
							"me/links",
							FacebookType.class,
							Parameter
									.with("link",
											"http://vnexpress.net/gl/the-gioi/cuoc-song-do-day/2012/02/obama-ngau-hung-hat-tai-nha-trang/"),
							Parameter.with("message", "test2"));
			System.out.println(response.getType());
			if (response.getId() != null && response.getId() != "") {
				return 1;
			} else {
				return 2;
			}
		} catch (Exception e) {
			log.error("FacebookPlugin.postMessage(String, String): error", e);
			return 3;
		}
	}

	public static int postMessage(String accessToken,
			SnsPostingInfo snsPostingInfo) {
		/*try {
			if (snsPostingInfo == null
					|| Helpers.isEmpty(snsPostingInfo.getPropertyKey())) {
				return SnSPostingStatus.FAIL;
			}
			FacebookClient facebookClient = new DefaultFacebookClient(
					accessToken);
			FacebookType response = null;
			if (snsPostingInfo.getPropertyKey().equals(
					Constants.SnSPostingType.SHARE_BET)
					|| snsPostingInfo.getPropertyKey().equals(
							Constants.SnSPostingType.CREATE_BET)) {
				String url = Helpers
						.getCgsProperty(com.zho.util.Constants.Address.FRONT_URL)
						+ "/bet/viewBet?betInfo.betId="
						+ snsPostingInfo.getPropertyValue();
				response = facebookClient.publish("me/links",
						FacebookType.class, Parameter.with("link", url));
			} else if (snsPostingInfo.getPropertyKey().equals(
					Constants.SnSPostingType.SHARE_EVENT)
					|| snsPostingInfo.getPropertyKey().equals(
							Constants.SnSPostingType.CREATE_EVENT)) {
				String url = Helpers
						.getCgsProperty(com.zho.util.Constants.Address.FRONT_URL)
						+ "/event/events?model.eventCondition.eventId="
						+ snsPostingInfo.getPropertyValue();
				response = facebookClient.publish("me/links",
						FacebookType.class, Parameter.with("link", url));
			} else if (snsPostingInfo.getPropertyKey().equals(
					Constants.SnSPostingType.SHARE_TOURNEY)
					|| snsPostingInfo.getPropertyKey().equals(
							Constants.SnSPostingType.CREATE_TOURNEY)) {
				String url = Helpers
						.getCgsProperty(com.zho.util.Constants.Address.FRONT_URL)
						+ "/tourney/viewTourney?tourneyInfo.tourneyId="
						+ snsPostingInfo.getPropertyValue();
				response = facebookClient.publish("me/links",
						FacebookType.class, Parameter.with("link", url));
			} else if (snsPostingInfo.getPropertyKey().equals(
					Constants.SnSPostingType.COMMENT_BET)) {

			} else if (snsPostingInfo.getPropertyKey().equals(
					Constants.SnSPostingType.COMMENT_EVENT)) {

			} else if (snsPostingInfo.getPropertyKey().equals(
					Constants.SnSPostingType.COMMENT_TOURNEY)) {

			} else if (snsPostingInfo.getPropertyKey().equals(
					Constants.SnSPostingType.JOIN_BET)) {
				String url = Helpers
						.getCgsProperty(com.zho.util.Constants.Address.FRONT_URL)
						+ "/bet/viewBet?betInfo.betId="
						+ snsPostingInfo.getPropertyValue()
						+ "&custBetPosInfo.custBetPosId="
						+ snsPostingInfo.getDescription();
				response = facebookClient.publish("me/links",
						FacebookType.class, Parameter.with("link", url),
						Parameter.with("message", "Joined the Bet"));
			} else if (snsPostingInfo.getPropertyKey().equals(
					Constants.SnSPostingType.NOTICE)) {
				
			}
			if (response == null) {
				return SnSPostingStatus.FAIL;
			}
			if (response.getId() != null && response.getId() != "") {
				return SnSPostingStatus.SUCCESS;
			} else {
				return SnSPostingStatus.FAIL;
			}
		} catch (Exception e) {
			log.error(
					"FacebookPlugin.postMessage(String, SnsPostingInfo): error",
					e);
			return SnSPostingStatus.FAIL;
		}
		*/
		return 0;
	}

	public static void main(String[] args) {
		try {
			FacebookClient facebookClient = new DefaultFacebookClient(
					"AAAEKnObXKO8BAGzxxL11rdrja8I45A2sCu3BLqYoGKSZC1FmjmaFoAZA4qCACS2pPK8CJV142CaMt9QZAwYWAUV6jBBTmuSUrZAsbRxRfQZDZD");
			// FacebookType response =
			// facebookClient.publish("368092876549085/comments ",
			// FacebookType.class, Parameter.with("message",
			// "test comment"));//Parameter.with("link",
			// "http://vnexpress.net/gl/the-gioi/cuoc-song-do-day/2012/02/obama-ngau-hung-hat-tai-nha-trang/"),
			Page response = facebookClient.fetchObject("19292868553",
					Page.class);
			System.out.println(response.getType());
			System.out.println(response.getId());
			// System.out.println(response.getLanguages());
		} catch (Exception e) {
			e.printStackTrace();
			log.error("FacebookPlugin.postMessage(String, String): error", e);
		}
	}

}
